<template>
    <view>
		<view class="page-bottom-fixed-">
			<!-- 导航 -->
			<view :class="'nav '+lang_info.app_lang">
				<scroll-view scroll-x="true" class="scroll-nav">
					<block v-for="(item, index) in nav_status_list" :key="index">
						<view :class="'item'+((nav_status_index == index) ? ' on' : '')" :data-index="index" @tap="nav_event">{{ item.name }}</view>
					</block>
				</scroll-view>
			</view>

			<!-- 订单列表 -->
			<scroll-view :scroll-y="true" class="scroll-box" @scrolltolower="scroll_lower" lower-threshold="30">
				<view class="list-content">
					<view class="list-item bg-white spacing-mb" v-if="data_list.length > 0" v-for="(item, index) in data_list" :key="index">
						<view class="item-base oh br-b">
							<text class="cr-666 fl">{{ item.add_time }}</text>
							<text class="cr-main">
								{{ item.status_name }}
								<text v-if="(item.is_under_line_text || null) != null">（{{ item.is_under_line_text }}）</text>
							</text>
						</view>

						<view class="goods-item br-b-dashed oh" v-for="(detail, index1) in item.items" :key="index1">
							<navigator :url="'/pages/fcc/groups/orderdetail/orderdetail?id=' + item.id" hover-class="none">
								<image class="goods-image fl radius" :src="detail.images" mode="aspectFill"></image>
								<view class="goods-base pr">
									<view class="multi-text">{{detail.title}}</view>
									<view v-if="detail.spec != null" class="margin-top-sm">
										<block v-for="(sv, si) in detail.spec" :key="si">
											<text v-if="si > 0" class="cr-grey padding-left-xs padding-right-xs">;</text>
											<text class="cr-grey">{{sv.value}}</text>
										</block>
									</view>                            
									<view class="margin-top-sm">
										<text class="fw-b">{{item.currency_data.currency_symbol}}{{detail.price}}</text>
										<text class="margin-left-sm">x{{detail.buy_number}}</text>
									</view>
									<view v-if="item.is_can_launch_aftersale == 1 && (detail.orderaftersale_btn_text || null) != null" class="orderaftersale-btn-text cr-blue pa bg-white" @tap.stop="orderaftersale_event" :data-oid="item.id" :data-did="detail.id">{{
										detail.orderaftersale_btn_text
									}}</view>
								</view>
							</navigator>
						</view>
	 
						<view class="item-describe tr cr-666">{{ item.describe }}</view>

						<!-- || (item.status == 2 && item.order_model != 2)-->

						<view v-if="item.status == 1 || item.status == 3 || (item.status == 4 && item.user_is_comments == 0) || (item.is_exist_bankext && item.bank_id > 0 && item.is_under_line == 1 && item.payment_flag == 'CashPayment')" class="item-operation tr br-t">
							<button v-if="item.status <= 1" class="round bg-white cr-yellow br-yellow margin-bottom-main" type="default" size="mini" @tap="cancel_event" :data-value="item.id" :data-index="index" hover-class="none">{{lang_info.order_list_btn_text_array.btn_cancel}}</button>
							<button v-if="item.status == 1" class="round bg-white cr-green br-green margin-bottom-main" type="default" size="mini" @tap="pay_event" :data-value="item.id" :data-index="index" :data-price="item.total_price" :data-payment="item.payment_id" :data-currency-symbol="item.currency_data.currency_symbol" hover-class="none">{{ item.is_under_line == 1 ? lang_info.order_list_btn_text_array.btn_change : lang_info.order_list_btn_text_array.btn_pay }}</button>
							
							<button v-if="is_have_express_plugins && item.order_model != 3 && (item.status == 3 || item.status == 4)" class="round bg-white cr-yellow br-yellow margin-bottom-main" type="default" size="mini" @tap="url_event" :data-value="'/pages/fcc/user-order-express/user-order-express?business_type=groupsorder&order_id='+item.id" :data-index="index" hover-class="none">{{lang_info.order_list_btn_text_array.btn_wuliu}}</button>
							
							<button v-if="item.status == 3" class="round bg-white cr-green br-green margin-bottom-main" type="default" size="mini" @tap="collect_event" :data-value="item.id" :data-index="index" hover-class="none">{{lang_info.order_list_btn_text_array.btn_shouhuo}}</button>
							<button v-if="item.status == 4 && item.user_is_comments == 0" class="round bg-white cr-green br-green margin-bottom-main" type="default" size="mini" @tap="comments_event" :data-value="item.id" :data-index="index" hover-class="none">{{lang_info.order_list_btn_text_array.btn_comment}}</button>
							<block v-if="item.is_exist_bankext && item.bank_id > 0 && item.is_under_line == 1 && item.payment_flag == 'CashPayment'">
								<button class="round bg-white cr-green br-green margin-bottom-main" type="default" size="mini" @tap="url_event" :data-value="'/pages/fcc/bankext/bankext?ids='+item.id+'&business_type=groupsorder'" :data-index="index" hover-class="none"><text v-if="item.is_bank_up == 0">{{$t('fengcheche.see_pingzheng')}}</text><text v-else>{{$t('fengcheche.up_pingzheng')}}</text></button>
							</block> 
							
							<button v-if="wuliu_type == 1 && (item.express_data || null) != null && item.express_data.length > 0" class="round bg-white cr-main br-main" type="default" size="mini" @tap="url_event" :data-value="'/pages/fcc/user-order-express/user-order-express?order_id=' + item.id + '&business_type=groupsorder'" hover-class="none">{{$t('orderallot-list.orderallot-list.w2t242')}}</button>
							<button v-if="wuliu_type == 2 && (item.express_data || null) != null && item.express_data.length > 0" class="round bg-white cr-main br-main" type="default" size="mini" @tap="url_event" :data-value="'/pages/fcc/aliquanqiuexpress/aliquanqiuexpress?order_id=' + item.id + '&business_type=groupsorder'" hover-class="none">{{$t('orderallot-list.orderallot-list.w2t242')}}</button>
						</view>
					</view>

					<view v-if="data_list.length == 0">
						<component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
					</view>

					<component-bottom-line :propStatus="data_bottom_line_status" :propMsg="lang_info.data_bottom_line_msg"></component-bottom-line>
				</view>
			</scroll-view>
			
			<!-- 结尾 -->
			<component-footer :propStatus="2"></component-footer>
		</view>
        
        <!-- 支付组件 -->
        <component-payment :diyTheme="diytheme" 
			 ref="payment"
            :propCurrencySymbol="currency_symbol"
            :propPayUrl="pay_url"
            :propQrcodeUrl="qrcode_url"
            :propPaymentList="payment_list"
            propPayDataKey="id"
            :propTempPayValue="temp_pay_value"
            :propTempPayIndex="temp_pay_index"
            :propPaymentId="payment_id"
            :propDefaultPaymentId="default_payment_id"
            :propPayPrice="pay_price"
            :propIsShowPayment="is_show_payment_popup"
            @close-payment-popup="payment_popup_event_close"
            @pay-success="order_item_pay_success_handle"
        ></component-payment>
    </view>
</template>

<script>
const app = getApp();
import base64 from '@/common/js/lib/base64.js';
import componentPopup from '@/components/popup/popup';
import componentQuickNav from "@/components/quick-nav/quick-nav";
import componentBadge from '@/components/badge/badge';
import componentNoData from "@/components/no-data/no-data";
import componentBottomLine from "@/components/bottom-line/bottom-line";
import componentPayment from '@/components/payment/payment';
import componentOnlineService from "@/components/online-service/online-service";
import componentFooter from "@/pages/fcc/groups/public/footer";
import { groups_base_info, clear_user_cach } from '@/pages/fcc/groups/public/common.js';

var groups_static_url = app.globalData.get_static_url('groups', true);
var common_static_url = app.globalData.get_static_url('common');
export default {
    components: {
        componentQuickNav,
        componentPopup,
        componentBadge,
        componentNoData,
        componentBottomLine,
        componentOnlineService,
		componentFooter,
		componentPayment
    },
    data() {
        return {
            currency_symbol: app.globalData.currency_symbol(),
            data_list: [],
            data_page_total: 0,
            data_page: 1,
            data_list_loding_status: 1,
            data_bottom_line_status: false,
			data_is_loading: 0,
            params: null,
            input_keyword_value: '',
			data_list_loding_msg: '',
            nav_status_list: [],
            nav_status_index: 0,
            data_total: '',
			diytheme:{
				'main_color':'#fd302d',
				'second_color':'#f29701',
				'ligth_color_1':'#feeaeb',
				'ligth_color_2':'#feeaeb',
				'ligth_color_deg':0,
				'price_color':'#fd302d',
			},
			pay_price: 0,
			pay_url: '',
			qrcode_url: '',
			payment_list: [],
			temp_pay_value: '',
			temp_pay_index: 0,
			payment_id: 0,
			default_payment_id: 0,
			is_show_payment_popup: false,
			// 智能工具箱（限定仅可选择下单支付方式）
			is_order_pay_only_can_buy_payment: 0,
			original_payment_list: [],
			order_select_ids: [],

			// 是否有物流插件
			is_have_express_plugins:false,
			
			site_for_pi:app.globalData.data.site_for_pi,
			
			// 多语言
			lang_info:{},
			wuliu_type: app.globalData.data.wuliu_type || 1,
        };
    },
    onLoad(params) {
		// 初始化params
		this.setData({
		    params: params,
		    nav_status_index: 0
		});
	},
	onShow() {
		// 数据加载
		this.init();
		this.get_other_data();
	},
    // 下拉刷新
    onPullDownRefresh() {
        this.setData({
            data_page: 1
        });
        this.get_data_list(1);
		this.get_other_data();
    },
    methods: {
		// 加载之前
		init() {
			// 先获取语言基础信息
			groups_base_info()
			.then(data=>{
				this.init_before(data)
				.then(()=>{
					this.init_real();
				});
			});
		},
		
		// 设置本页参数
		init_before(data){
			var self = this;
			return new Promise((resolve, reject) => {
				self.setData({
					lang_info:data,
					currency_symbol: app.globalData.get_config('currency_symbol'),
					nav_status_list:data.order_list_status_list_array,
					is_order_pay_only_can_buy_payment: parseInt(app.globalData.get_config('plugins_base.intellectstools.data.is_order_pay_only_can_buy_payment', 0)),
					pay_url: app.globalData.get_request_url('pay', 'index', 'groups'),
					qrcode_url: app.globalData.get_request_url('paycheck', 'index', 'groups'),
					common_app_is_online_service: app.globalData.get_config('config.common_app_is_online_service'),
				});
				uni.setNavigationBarTitle({
				    title: data.order_list_page_title
				});
				resolve();
			});
		},
        init_real() {
			// 是否指定状态
			var nav_status_index = 0;
			if ((this.params || null) != null && (this.params.status || null) != null) {
			    for (var i in this.nav_status_list) {
			        if (this.nav_status_list[i]['value'] == this.params.status) {
			            nav_status_index = i;
			            break;
			        }
			    }
			}
			this.setData({
			    nav_status_index: nav_status_index
			});

            var user = app.globalData.get_user_info(this, 'init');
            if (user != false) {
				this.get_other_data()
				.then(()=>{
					// 获取数据
					this.get_data_list(1);
				});
            } else {
                this.setData({
                    data_list_loding_status: 0,
                    data_bottom_line_status: false
                });
            }
        },

        // 输入框事件
        input_event(e) {
            this.setData({
                input_keyword_value: e.detail.value
            });
        },

        // 获取数据
        get_data_list(is_mandatory) {
            // 分页是否还有数据
            if ((is_mandatory || 0) == 0) {
                if (this.data_bottom_line_status == true) {
					uni.stopPullDownRefresh();
					return false;
				}
			}

			// 是否加载中
			if (this.data_is_loading == 1) {
				return false;
			}
			this.setData({
				data_is_loading: 1,
				data_list_loding_status: 1,
			});

			// 加载loding
			uni.showLoading({
				title: this.$t('common.loading_in_text'),
			});
	    
			// 参数
            var order_status = (this.nav_status_list[this.nav_status_index] || null) == null ? -1 : this.nav_status_list[this.nav_status_index]['value']; // 获取数据
			var self = this;
            uni.request({
                url: app.globalData.get_request_url('orderlist', 'index', 'groups'),
                method: 'POST',
                data: {
                    page: this.data_page,
                    keywords: this.input_keyword_value || '',
                    status: order_status,
                    is_more: 1
                },
                dataType: 'json',
                success: (res) => {
                    console.log(res);
                    uni.hideLoading();
                    uni.stopPullDownRefresh();

                    if (res.data.code == 0) {
                        if (res.data.data.data.length > 0) {
                            if (this.data_page <= 1) {
                                var temp_data_list = res.data.data.data; 
                            } else {
                                var temp_data_list = this.data_list || [];
                                var temp_data = res.data.data.data;

                                for (var i in temp_data) {
                                    temp_data_list.push(temp_data[i]);
                                }
                            }

                            this.setData({
								original_payment_list: res.data.data.payment_list || [],
								payment_list: res.data.data.payment_list || [],
								default_payment_id: res.data.data.default_payment_id || 0,
                                data_list: temp_data_list,
                                data_total: res.data.data.total,
                                data_page_total: res.data.data.page_total,
                                data_list_loding_status: 3,
                                data_page: this.data_page + 1,
                                data_is_loading: 0
                            }); 
			    
							// 是否还有数据
							this.setData({
								data_bottom_line_status: this.data_page > 1 && this.data_page > this.data_page_total,
							});
				
							// 下订单支付处理
							var key = app.globalData.data.cache_page_pay_key;
							var pay_data = uni.getStorageSync(key) || null;
							if (pay_data != null && (pay_data.order_ids || null) != null && (pay_data.payment_id || null) != null) {
								uni.removeStorageSync(key);
								this.setData({
									temp_pay_value: pay_data.order_ids,
									payment_id: pay_data.payment_id,
								});
								if ((this.$refs.payment || null) != null) {
									this.$refs.payment.pay_handle(pay_data.order_ids, pay_data.payment_id, this.original_payment_list);
								}
							}
                        } else {
                            this.setData({
								data_list_loding_status: 0,
								data_bottom_line_status: false,
								data_list: [],
								data_is_loading: 0,
                            });
                        }
                    } else {
						// 如果是前端有登录信息，后端session已被清理缓存，这此处处理掉前端缓存，重新授权
						/*if(res.data.code == -400){
							clear_user_cach().then(()=>{
								self.get_data_list();
							});
							return false;
						}*/
                        this.setData({
                            data_list_loding_status: 0,
                            data_is_loading: 0,
                        });

                        if (app.globalData.is_login_check(res.data, this, 'get_data_list')) {
                            app.globalData.showToast(res.data.msg);
                        }
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    this.setData({
                        data_list_loding_status: 2,
                        data_is_loading: 0,
                    });
                    app.globalData.showToast(this.$t('common.internet_error_tips'));
                }
            });
        },
		
		// 支付参数+红包数据单独调用
		get_other_data() {
			return new Promise((resolve, reject) => {
				uni.request({
					url: app.globalData.get_request_url('otherdata', 'index', 'groups'),
					method: 'POST',
					data: {
					},
					dataType: 'json',
					success: (res) => {
						console.log(res);
						if (res.data.code == 0) {
							this.setData({
								payment_list: res.data.data.payment_list || [],
								is_have_express_plugins:res.data.data.is_have_express_plugins || false,
							});
							resolve();
						} else {
							if(res.data.code == -400)
							{
								clear_user_cach()
								.then(()=>{
									this.init();
								});
								return false;
							}else{
								app.globalData.showToast(res.data.msg);
								// 失败返回失败结果
								reject(res.data.msg)
							}
						}
					},
					fail: () => {
						uni.stopPullDownRefresh();
						app.globalData.showToast(this.lang_info.request_data_error_tips);
						reject(this.lang_info.request_data_error_tips)
					}
				});
			});
		},

        // 滚动加载
        scroll_lower(e) {
            this.get_data_list();
        },

        // 支付
        pay_event(e) {
			// 参数
			var index = e.currentTarget.dataset.index || 0;
			var payment_id = e.currentTarget.dataset.payment || 0;
			
			// 智能工具箱（限定仅可选择下单支付方式）
			if(this.is_order_pay_only_can_buy_payment == 1) {
			    var payment_list = [];
			    this.original_payment_list.forEach(function(v, k) {
			        if(v.id == payment_id) {
			            payment_list.push(v);
			        }
			    });
			} else {
			    var payment_list = this.original_payment_list;
			}
			
			// 设置支付参数
			this.setData({
			    is_show_payment_popup: true,
			    payment_list: payment_list,
			    currency_symbol: e.currentTarget.dataset.currencySymbol,
			    temp_pay_value: e.currentTarget.dataset.value,
			    temp_pay_index: index,
			    payment_id: payment_id,
			    pay_price: e.currentTarget.dataset.price,
			    order_select_ids: [],
			});
        },

        // 支付弹窗关闭
        payment_popup_event_close(e) {
            this.setData({
                is_show_payment_popup: false
            });
        },
        // 支付成功数据设置
		// 订单完成回调
		order_item_pay_success_handle(data) {
			var order_ids_arr = data.order_id.toString().split(',');
			var temp_data_list = this.data_list;
			for (var i in temp_data_list) {
				if (order_ids_arr.indexOf(temp_data_list[i]['id'].toString()) != -1) {
					//temp_data_list[i]['operate_data']['is_pay'] = 0;
					//temp_data_list[i]['operate_data']['is_cancel'] = 0;
					temp_data_list[i]['status'] = 2;
					switch (parseInt(temp_data_list[i]['order_model'])) {
						// 销售模式
						case 0:
							temp_data_list[i]['status_name'] = this.$t('user.user.66714e');
							break;
						// 自提模式
						case 2:
							temp_data_list[i]['status_name'] = this.$t('user-order.user-order.hp123x');
							break;
						// 虚拟模式-拼团付款后并不会直接触发发货，拼团成功才会触发
						case 3:
							temp_data_list[i]['status_name'] = this.$t('user.user.66714e');
							break;
					}
				}
			}
			this.setData({
				data_list: temp_data_list,
			});
		},

		// 取消
		cancel_event(e) {
			uni.showModal({
				title: this.$t('common.warm_tips'),
				content: this.$t('order.order.pn78ns'),
				confirmText: this.$t('common.confirm'),
				cancelText: this.$t('recommend-list.recommend-list.w9460o'),
				success: (result) => {
					if (result.confirm) {
						// 参数
						var id = e.currentTarget.dataset.value;
						var index = e.currentTarget.dataset.index;

						// 加载loding
						uni.showLoading({
							title: this.$t('common.processing_in_text'),
						});
						uni.request({
							url: app.globalData.get_request_url('cancel', 'index', 'groups'),
							method: 'POST',
							data: {
								id: id,
							},
							dataType: 'json',
							success: (res) => {
								uni.hideLoading();
								if (res.data.code == 0) {
									var temp_data_list = this.data_list;
									temp_data_list[index]['status'] = 5;
									temp_data_list[index]['status_name'] = this.$t('order.order.1k98tk');
									/*temp_data_list[index]['operate_data']['is_cancel'] = 0;
									temp_data_list[index]['operate_data']['is_pay'] = 0;
									temp_data_list[index]['operate_data']['is_delete'] = 1;*/
									temp_data_list[index]['is_can_launch_aftersale'] = 0;
									this.setData({
										data_list: temp_data_list,
									});
									app.globalData.showToast(res.data.msg, 'success');
								} else {
									app.globalData.showToast(res.data.msg);
								}
							},
							fail: () => {
								uni.hideLoading();
								app.globalData.showToast(this.$t('common.internet_error_tips'));
							},
						});
					}
				},
			});
		},

		// 收货
		collect_event(e) {
			uni.showModal({
				title: this.$t('common.warm_tips'),
				content: this.$t('orderallot-list.orderallot-list.o3ouqv'),
				confirmText: this.$t('common.confirm'),
				cancelText: this.$t('recommend-list.recommend-list.w9460o'),
				success: (result) => {
					if (result.confirm) {
						// 参数
						var id = e.currentTarget.dataset.value;
						var index = e.currentTarget.dataset.index;

						// 加载loding
						uni.showLoading({
							title: this.$t('common.processing_in_text'),
						});
						uni.request({
							url: app.globalData.get_request_url('collect', 'index', 'groups'),
							method: 'POST',
							data: {
								id: id,
							},
							dataType: 'json',
							success: (res) => {
								uni.hideLoading();
								if (res.data.code == 0) {
									var temp_data_list = this.data_list;
									temp_data_list[index]['status'] = 4;
									temp_data_list[index]['status_name'] = this.$t('order.order.15lr5l');
									/*temp_data_list[index]['operate_data']['is_collect'] = 0;
									temp_data_list[index]['operate_data']['is_comments'] = 1;
									temp_data_list[index]['operate_data']['is_delete'] = 1;*/
									this.setData({
										data_list: temp_data_list,
									});
									app.globalData.showToast(res.data.msg, 'success');
								} else {
									app.globalData.showToast(res.data.msg);
								}
							},
							fail: () => {
								uni.hideLoading();
								app.globalData.showToast(this.$t('common.internet_error_tips'));
							},
						});
					}
				},
			});
		},

        // 催催
        rush_event(e) {
            app.globalData.showToast(this.$t('user-order.user-order.f5qqhu'), 'success');
        },

		// 导航事件
		nav_event(e) {
			this.setData({
				nav_status_index: e.currentTarget.dataset.index || 0,
				data_page: 1,
				order_select_ids: [],
			});

			// 重新拉取数据
			this.get_data_list(1);
		},


        // 售后订单事件
        orderaftersale_event(e) {
            var oid = e.currentTarget.dataset.oid || 0;
            var did = e.currentTarget.dataset.did || 0;

            if (oid == 0 || did == 0) {
                    app.globalData.showToast(this.$t('user-order-detail.user-order-detail.5k6k56'));
                return false;
            }
			
			// 进入售后页面
            app.globalData.url_open('/pages/fcc/groups/orderaftersaledetail/orderaftersaledetail?oid=' + oid + '&did=' + did);
        },

        // 订单评论 
        comments_event(e) {
            app.globalData.url_open('/pages/fcc/groups/comment/comment?id=' + e.currentTarget.dataset.value);
        },
		
		// 页面卸载
		onUnload(e) {
		    clearInterval(this.popup_view_pay_timer);
		},
		
		// url事件
		url_event(e) {
		    app.globalData.url_event(e);
		}
    }
};
</script>
<style>
@import './order.css';
</style>
